package com.example.demo.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.Exception.BackErrorException;
import com.example.demo.entity.*;
import com.example.demo.entity.requestJson.UregisterReq;
import com.example.demo.enums.ErrCodeEnum;
import com.example.demo.mapper.*;
import com.example.demo.service.ARegistService;
import com.example.demo.tools.Md5utils;
import com.example.demo.tools.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.UUID;

@Service
@Transactional(rollbackFor = {RuntimeException.class, Exception.class})
public class ARegistServiceImpl  implements ARegistService {
    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private RegistMapper registMapper;
    @Autowired
    private AuthorMapper authorMapper;
    @Autowired
    private BookshelefMapper bookshelefMapper;
    @Autowired
    private WalletMapper walletMapper;

    /**
     * 1.登陆表id与信息表id一样，是用户或作者的凭证，
     * 2.注册成功登录时自动生成登录表id，并根据角色，将此条信息自动插入到相应的信息表中，此后再更新信息表中的其他信息；
     * 3.登录成功之后自动生成昵称存入信息表中，用户可自行修改
     * */
    @Override
    public BackResponseEntity<Object> userRegist (UregisterReq uregisterReq) throws BackErrorException {
        String phone = null;
        String code = null;
        String pwd = null;
        String confirmpwd = null;

        if (!ObjectUtils.isEmpty(uregisterReq.getRegisterPhone())) {
            phone =uregisterReq.getRegisterPhone()
                    .trim();
        }
        if (!ObjectUtils.isEmpty(uregisterReq.getVerifyCode())) {
            code =uregisterReq.getVerifyCode()
                    .trim();
        }
        if (!ObjectUtils.isEmpty(uregisterReq.getLoginPwd())) {
            pwd =uregisterReq.getLoginPwd()
                    .trim();
        }
        if (!ObjectUtils.isEmpty(uregisterReq.getConfirmLoginPwd())) {
            confirmpwd =uregisterReq.getConfirmLoginPwd()
                    .trim();
        }



        if(ObjectUtils.isEmpty(phone) || ObjectUtils.isEmpty(code) || ObjectUtils.isEmpty(pwd) || ObjectUtils.isEmpty(confirmpwd)){

            return BackResponseEntity.success(ErrCodeEnum.unknown_4006,"参数缺失");
        }

        Object verifyDataObject = redisUtil.get(phone + "SMS:authors");
        if (!ObjectUtils.isEmpty(verifyDataObject)) {
            String verifyData = (String) verifyDataObject;
            if (!code.equals(verifyData)) {
                return BackResponseEntity.success(ErrCodeEnum.unknown_1001,"验证码错误");
            }
        }else {
            return BackResponseEntity.success(ErrCodeEnum.unknown_1000,"验证码过期");
        }
        if(!confirmpwd.equals(pwd)){
            return BackResponseEntity.success(ErrCodeEnum.unknown_1002,"两次输入密码不一致");
        }

        String loginPwd = Md5utils.getmd5Lowercase("qingyu" + pwd);
        String nickname = "小猫咪"+ UUID.randomUUID().toString().replace("-","").substring(0,5);
        String bookshelfId = (int)((Math.random()*9+1)*1000) + UUID.randomUUID().toString().replace("-","").substring(0,10);
        Login login = new Login();
        Login loginres = loginMapper.queryLoginLimit1(login);

        if(!ObjectUtils.isEmpty(loginres) && phone.equals(loginres.getLoginPhone())){
            return BackResponseEntity.success(ErrCodeEnum.unknown_1003,"该手机号已注册，请直接登录");
        }

        LocalDateTime time = LocalDateTime.now();
        String pic = "https://dss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=128476812,2256985719&fm=26&gp=0.jpg";
        login.setLoginPwd(loginPwd);
        login.setLoginNickname(nickname);
        login.setLoginPhone(phone);
        login.setRegistTime(time);
        login.setLoginRole(0);
        login.setLoginPic(pic);
        login.setBookshelfId(bookshelfId);

        int i = loginMapper.insert(login);

        Login registedRes = registMapper.queryRegisted(phone);

        Bookshelef bookshelef = new Bookshelef();
        bookshelef.setUserId(registedRes.getLoginId());
        bookshelefMapper.insert(bookshelef);

        Bookshelef bookshelef1 = new Bookshelef();
        LambdaQueryWrapper<Bookshelef> wrapper = new QueryWrapper<Bookshelef>().lambda();
        wrapper.select(Bookshelef::getBookshelfId)
                .eq(Bookshelef::getUserId,registedRes.getLoginId());
        bookshelef1 = bookshelefMapper.selectOne(wrapper);

        Author author = new Author();
        author.setAuthorId(registedRes.getLoginId());
        author.setAregistTime(time);
        author.setAuthorNickname(nickname);
        author.setAuthorPhone(phone);
        author.setAuthorImg(pic);
        author.setAttentionCount(0);
        author.setReaderCount(0);
        author.setUpdateCount(3);
        author.setTotalWords(0);
        author.setAcommentStatus(0);
        author.setAloginStatus(0);
        author.setBookshelfId(bookshelef.getBookshelfId());
        authorMapper.insert(author);

        Wallet wallet = new Wallet();
        wallet.setUserId(registedRes.getLoginId());
        wallet.setCanCount(0);
        wallet.setCatfoodCount(0);
        wallet.setFishCount(0);
        wallet.setRole(0);
        wallet.setIncome(BigDecimal.valueOf(0.00));
        walletMapper.insert(wallet);
        if(i > 0){
            return BackResponseEntity.success(ErrCodeEnum.unknown_0,"恭喜您注册成功");
        }else {
            return BackResponseEntity.success(ErrCodeEnum.unknown_1004,"注册失败");
        }

    }

}
